<?php
namespace app\mode\email;

use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
class Email
{
    private PHPMailer $mailer;

    private bool $isHTML = false;

    private array $config = [];

    public function __construct()
    {
        $this->mailer  = new PHPMailer();
    }

    private function setConfig($configName)
    {
        $this->config = config('common.email.' . $configName) ? : config('common.email.qq');
        $this->setupMailer();
    }

    public function setupMailer()
    {
        $this->mailer->isSMTP();
        $this->mailer->Host = $this->config['host']; // 你的SMTP服务器地址
        $this->mailer->SMTPAuth = true;
        $this->mailer->Username = $this->config['username']; // SMTP用户名
        $this->mailer->Password = $this->config['password']; // SMTP密码
        $this->mailer->SMTPSecure = $this->config['encryption']; // TLS安全连接
        $this->mailer->Port = $this->config['port']; // 你的SMTP端口号
        $this->mailer->CharSet = 'UTF-8';
        $this->mailer->SMTPDebug = 0; // 设置为1或2进行调试
    }

    public function isHTML(): Email
    {
        $this->mailer->isHTML();
        $this->isHTML = true;
        return $this;
    }

    /**
     * 发送邮件
     * @param string $email
     * @param string $content
     * @param string $title
     * @return array
     */
    public function send(string $email, string $content, string $title): array
    {
        try {
            //从后面开始查找.
            $this->setConfig(substr($email, strrpos($email, '@') + 1, (strrpos($email, '.') - strrpos($email, '@') - 1)));
            $this->mailer->setFrom($this->mailer->Username, getSettingOptionsCache('base.web_site_title', '后台管理系统')); // 发起人信息
            $this->mailer->addAddress($email); // 收件人邮箱地址
            $this->mailer->Subject = getSettingOptionsCache('base.web_site_title', '后台管理系统') . '-' . $title; // 标题
            $this->isHTML ? $this->mailer->MsgHTML($content) : $this->mailer->Body = $content;
            return $this->mailer->send() ? responseArrayMsg('发送成功', 200) : responseArrayMsg('发送失败，原因：' . $this->mailer->ErrorInfo);
        } catch (Exception $e) {
            return responseArrayMsg('发送失败，原因：' . $e->getMessage());
        }
    }
}